package com.alibaba.otter.manager.biz.autoconfigure;

import com.alibaba.otter.common.push.datasource.DataSourceHandler;
import com.alibaba.otter.common.push.datasource.media.MediaPushDataSourceHandler;
import com.alibaba.otter.manager.biz.autoconfigure.properties.ManagerProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.net.ssl.SSLSocketFactory;
import java.util.Properties;

@Configuration(proxyBeanMethods = false)
public class OtterConfiguration {


    @Bean
    public DataSourceHandler dataSourceHandler(){
        return new MediaPushDataSourceHandler();
    }


    @Configuration
    @ConditionalOnClass(ManagerProperties.class)
    static class MailConfiguration{

        @Bean
        public JavaMailSender javaMailSender(ManagerProperties managerProperties){

            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

            javaMailSender.setHost(managerProperties.getMonitor().getEmail().getHost());
            javaMailSender.setPassword(managerProperties.getMonitor().getEmail().getPassword());
            javaMailSender.setUsername(managerProperties.getMonitor().getEmail().getUsername());
            javaMailSender.setPort(managerProperties.getMonitor().getEmail().getSmtp().getPort());
            javaMailSender.setDefaultEncoding(managerProperties.getMonitor().getEmail().getEncoding());

            Properties properties = new Properties();

            properties.setProperty("mail.smtp.auth","true");
            properties.setProperty("mail.smtp.timeout","25000");
            properties.setProperty("mail.smtp.socketFactory.port",managerProperties.getMonitor().getEmail().getSmtp().getPort().toString());
            properties.setProperty("mail.smtp.socketFactory.fallback","false");
            properties.setProperty("mail.smtp.socketFactory.class", SSLSocketFactory.class.getName());
            javaMailSender.setJavaMailProperties(properties);


            return javaMailSender;
        }

    }
}
